<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2017/1/5
 * Time: 下午2:43
 */

namespace EWeiLink\JuPai;

use Illuminate\Support\Facades\Route;

define('PLUGIN_DB_NAME', 'plugin_jp');

class JuPai
{
    const alias = 'jp';
    const plugin_database_name = PLUGIN_DB_NAME;

    static $config = [];

    static function init(array $config = null)
    {
        if (!is_null($config)) {
            static::$config = $config;
        }
    }

    /**
     * @return bool
     */
    static function checkDomain()
    {
        if ('cli' === php_sapi_name()) { // 如果是cli模式，直接返回false
            return false;
        }

        if (isset($_SERVER["HTTP_HOST"])) { // 必须有HTTP_HOST的值，才能继续
            $serverHosts = explode('.', $_SERVER["HTTP_HOST"]);
            $subDomain = current($serverHosts);
            return $subDomain === static::alias;
        }
        return false;
    }

    /**
     * @param array $options
     */
    static function routes($callback = null, array $options = [])
    {
        $callback = $callback ?? function(RouteRegistrar $router) {
            $router->all();
        };

        $options = array_merge($options, [
            'namespaces' => '\EWeiLink\JuPai\Http\Controllers',
        ]);

        Route::group($options, function($router) use ($callback) {
           $callback(new RouteRegistrar($router));
        });
    }

    public function connectionConfig(array $default)
    {
       return array_merge($default, ['database' => static::plugin_database_name]);
    }

    static function callBridgeHelper($func_name, array $params)
    {
        $bridgeServiceName = 'App\Services\HelpService';
        if (class_exists($bridgeServiceName) && method_exists($bridgeServiceName, $func_name)) {
            return call_user_func_array([$bridgeServiceName, $func_name], $params);
        }
        return null;
    }

    static function makeBridgeClass($class, array $params = null)
    {
        if (class_exists($class)) {
            $ref = new \ReflectionClass($class);
            if (is_null($params)){
                return $ref->newInstance();
            }
            return $ref->newInstanceArgs($params);
        }
        return null;
    }
}